package com.link.play.fit.ai.ui.main.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.link.play.fit.ai.R
import com.link.play.fit.ai.bean.ControlDayData
import com.link.play.fit.ai.databinding.ControlItemPageContainerBinding
import com.link.play.fit.ai.databinding.ControlListItemLayoutBinding

class DayPagerAdapter(
    val data: List<ControlDayData>,val onclick:(Int) -> Unit
) : RecyclerView.Adapter<DayPagerAdapter.PageViewHolder>() {

    // 分页后的数据（每页7项）
    private var pagedData = data.chunked(7)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.control_item_page_container, parent, false)
        return PageViewHolder(view)
    }

    override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
        holder.bind(pagedData[position],position)
//        holder.itemBinding.pageRecyclerView
    }

    override fun getItemCount() = pagedData.size

    inner class PageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val recyclerView: RecyclerView = view.findViewById(R.id.pageRecyclerView)
//        var itemBinding: ControlItemPageContainerBinding =
//            ControlItemPageContainerBinding.bind(itemView)
        fun bind(pageData: List<ControlDayData>,position: Int) {
            recyclerView.apply {
                layoutManager = GridLayoutManager(context, 7)

                adapter = DayItemAdapter(pageData,position,context,{ p->

                    val globalIndex = position * 7 + p
                    onclick.invoke(globalIndex)
//                    onGlobalItemClick(globalIndex)

                    data.forEachIndexed { index, controlDayData ->
                        if(index == p){
                            controlDayData.currentPosition = p
                        }else{
                            controlDayData.currentPosition = -1
                        }
                    }
                    pagedData = data.chunked(7)
                    notifyDataSetChanged()
                })

            }
        }
    }
}
